package com.deep.sftp;


import com.jcraft.jsch.ChannelSftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author: chenly
 * @date: 2022-11-01 11:18
 * @description:
 * @version: 1.0
 */
@Slf4j
@RestController
public class SftpController {

    @Resource
    private SftpObjectPool sftpPool;

    @Resource
    private SftpProperties sftpProperties;


    @GetMapping("/file/download2")
    public ResponseEntity<FileSystemResource> fileDownload2(@RequestParam String fileName) {
        SftpClientObject sftpClient = null;
        try {
            log.info("sftp连接池大小{}", sftpPool.getNumIdle());
            sftpClient = sftpPool.borrowObject();
            ChannelSftp sftp = sftpClient.getSftp();
            InputStream inputStream = sftp.get("/test1/" + fileName);
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // 设置响应头信息，包括文件名和文件类型
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            String filePath = System.getProperty("user.dir") + "/uploads/" + fileName;
            System.out.println(filePath);
            File file = new File(filePath);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int l1;
            while((l1 = inputStream.read(b)) != -1) {
                fileOutputStream.write(b, 0, l1);
            }
            inputStream.close();
            fileOutputStream.close();

            // 返回文件资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new FileSystemResource(file));

        } catch (Exception e1) {
            log.info("下载异常！", e1);
            try {
                sftpPool.invalidateObject(sftpClient);
            } catch (Exception e2) {
                log.info("销毁sftp连接异常！", e2);
            }
            sftpClient = null;
        } finally {
            if (null != sftpClient) {
                sftpPool.returnObject(sftpClient);
            }
        }
        return null;
    }


    @GetMapping("/file/download")
    public ResponseEntity<FileSystemResource> fileDownload() {
        SftpClientObject sftpClient = null;
        try {
            log.info("sftp连接池大小{}", sftpPool.getNumIdle());
            sftpClient = sftpPool.borrowObject();
            ChannelSftp sftp = sftpClient.getSftp();
            InputStream inputStream = sftp.get("/test1/a.txt");
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            String fileName = "a.txt";
            // 设置响应头信息，包括文件名和文件类型
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            String filePath = System.getProperty("user.dir") + "/uploads/" + fileName;
            System.out.println(filePath);
            File file = new File(filePath);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int l1;
            while((l1 = inputStream.read(b)) != -1) {
                fileOutputStream.write(b, 0, l1);
            }
            inputStream.close();
            fileOutputStream.close();

            // 返回文件资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new FileSystemResource(file));

        } catch (Exception e1) {
            log.info("下载异常！", e1);
            try {
                sftpPool.invalidateObject(sftpClient);
            } catch (Exception e2) {
                log.info("销毁sftp连接异常！", e2);
            }
            sftpClient = null;
        } finally {
            if (null != sftpClient) {
                sftpPool.returnObject(sftpClient);
            }
        }
        return null;
    }

    @GetMapping("/file/txtSize")
    public Integer txtSize() {
        SftpClientObject sftpClient = null;
        try {
            log.info("sftp连接池大小{}", sftpPool.getNumIdle());
            sftpClient = sftpPool.borrowObject();
            ChannelSftp sftp = sftpClient.getSftp();
            InputStream inputStream = sftp.get("/test1/a.txt");
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, byteArrayOutputStream);
            return byteArrayOutputStream.size();
        } catch (Exception e1) {
            log.info("下载异常！", e1);
            try {
                sftpPool.invalidateObject(sftpClient);
            } catch (Exception e2) {
                log.info("销毁sftp连接异常！", e2);
            }
            sftpClient = null;
        } finally {
            if (null != sftpClient) {
                sftpPool.returnObject(sftpClient);
            }
        }
        return null;
    }
}